import { useEffect, useState } from 'react';
import { Layout, Tree, Table, Card, Space, Button, Form, Modal, Tag, App, Input } from 'antd';
import { 
  getDepartmentTree, 
  addDepartment, 
  updateDepartment, 
  deleteDepartment,
  getDepartmentById
} from '@/api/department';
import { getUserList, addUser, updateUser, getUserById, deleteUser,resetUserPassword } from '@/api/user';
import { getDictByCode } from '@/api/dict';
import { 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined,
  UserOutlined,
  SearchOutlined,
  RetweetOutlined
} from '@ant-design/icons';
import DepartmentForm from './DepartmentForm';
import UserForm from './UserForm';

import AuthControl from '@/components/common/AuthControl';

const { Sider, Content } = Layout;

import hasElementAuth from '@/utils/auth';

const DepartmentIndex = () => {
  const { modal,message } = App.useApp();
  const [departments, setDepartments] = useState([]);
  const [users, setUsers] = useState([]);
  const [roles, setRoles] = useState([]);
  const [selectedDepartment, setSelectedDepartment] = useState(null);
  const [loading, setLoading] = useState(false);
  const [userLoading, setUserLoading] = useState(false);
  const [departmentForm] = Form.useForm();
  const [userForm] = Form.useForm();
  const [userSearchForm] = Form.useForm();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isUserModalVisible, setIsUserModalVisible] = useState(false);
  const [modalType, setModalType] = useState('add'); // 'add' 或 'edit'
  const [userModalType, setUserModalType] = useState('add'); // 'add' 或 'edit'

  // 分页状态
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  // 获取部门树
  const fetchDepartments = () => {
    setLoading(true);
    getDepartmentTree().then(res => {
      if (res.data) {
        setDepartments(res.data);
      }
    }).finally(() => {
      setLoading(false);
    });
  };

  // 获取角色列表
  const fetchRoles = () => {
    getDictByCode('admin',{dictCode:'role'}).then(res => {
      if (res.data) {
        setRoles(res.data.others || []);
      }
    });
  };

  // 获取用户列表
  const fetchUsers = (departmentId, page = 1, size = 10, searchParams = {}) => {
    if (!departmentId) return;
    
    setUserLoading(true);
    // 根据 UserSearchVo 定义构建参数
    const params = {
      departmentId: departmentId,
      current: page,
      size: size,
      ...searchParams
    };
    
    return getUserList(params).then(res => {
      if (res.data) {
        setUsers(res.data.others || []);
        setPagination({
          current: res.data.current,
          pageSize: res.data.size,
          total: res.data.total
        });
      }
    }).catch(error => {
      console.error('获取用户列表失败:', error);
    }).finally(() => {
      setUserLoading(false);
    });
  };

  // 处理部门选择
  const handleDepartmentSelect = (selectedKeys) => {
    if (selectedKeys.length > 0) {
      const departmentId = selectedKeys[0];
      setSelectedDepartment(departmentId);
      // 重置搜索条件并获取用户列表
      userSearchForm.resetFields();
      fetchUsers(departmentId);
    } else {
      setSelectedDepartment(null);
      setUsers([]);
    }
  };

  // 显示添加部门模态框
  const showAddModal = () => {
    setModalType('add');
    departmentForm.resetFields();
    // 如果已选择部门，则设置为新部门的父级
    if (selectedDepartment) {
      departmentForm.setFieldsValue({
        pid: selectedDepartment
      });
    }
    setIsModalVisible(true);
  };

  // 显示编辑部门模态框
  const showEditModal = () => {
    if (!selectedDepartment) return;
    
    setModalType('edit');
    // 调用接口获取部门详细信息
    getDepartmentById(selectedDepartment).then(res => {
      if (res.data) {
        departmentForm.setFieldsValue({
          id: res.data.id,
          departmentName: res.data.departmentName,
          remark: res.data.remark,
          pid: res.data.pid
        });
        setIsModalVisible(true);
      }
    }).catch(error => {
      console.error('获取部门详情失败:', error);
      // 即使获取详情失败，也显示模态框
      departmentForm.setFieldsValue({
        id: selectedDepartment
      });
      setIsModalVisible(true);
    });
  };

  // 处理部门提交
  const handleDepartmentSubmit = (values) => {
      if (modalType === 'add') {
        addDepartment(values).then(() => {
          setIsModalVisible(false);
          departmentForm.resetFields();
          fetchDepartments();
          message.success("部门添加成功！");
        });
      } else {
        updateDepartment(values).then(() => {
          setIsModalVisible(false);
          departmentForm.resetFields();
          fetchDepartments();
          message.success("部门更新成功！");
        });
      }
  };

  // 删除部门
  const handleDeleteDepartment = () => {
    if (!selectedDepartment) return;
    modal.confirm({
      title: '确认删除',
      content: '确定要删除这个部门吗？',
      onOk: () => {
        deleteDepartment(selectedDepartment).then(() => {
          fetchDepartments();
          setSelectedDepartment(null);
          setUsers([]);
          message.success("部门删除成功！");
        });
      }
    });
  };

  // 显示添加用户模态框
  const showAddUserModal = () => {
    if (!selectedDepartment) return;
    
    setUserModalType('add');
    userForm.resetFields();
    userForm.setFieldsValue({
      departmentId: selectedDepartment
    });
    setIsUserModalVisible(true);
  };

  // 显示编辑用户模态框
  const showEditUserModal = (record) => {
    setUserModalType('edit');
    getUserById(record.userId).then(res => {
      if (res.data) {        
        userForm.setFieldsValue({
          userId: res.data.userId,
          username: res.data.username,
          nickname: res.data.nickname,
          gender: res.data.gender,
          phone: res.data.phone,
          departmentId: res.data.departmentId,
          roleId: res.data.roleId,
          remark: res.data.remark,
          avatar: res.data.avatar
        });
        setIsUserModalVisible(true);
      }
    });
  };

  // 处理用户提交
  const handleUserSubmit = (values) => {
    if (userModalType === 'add') {
      addUser(values).then(() => {
        setIsUserModalVisible(false);
        userForm.resetFields();
        // 刷新用户列表
        if (selectedDepartment) {
          fetchUsers(selectedDepartment);
        }
        message.success("用户添加成功！");
      });
    } else {
      updateUser(values).then(() => {
        setIsUserModalVisible(false);
        userForm.resetFields();
        // 刷新用户列表
        if (selectedDepartment) {
          fetchUsers(selectedDepartment);
        }
        message.success("用户更新成功！");
      });
    }
  };

  // 删除用户
  const handleDeleteUser = (userId) => {
    modal.confirm({
      title: '确认删除',
      content: '确定要删除这个用户吗？',
      onOk: () => {
        deleteUser(userId).then(() => {
          message.success("用户删除成功！");
          // 刷新用户列表
          if (selectedDepartment) {
            fetchUsers(selectedDepartment);
          }
        });
      }
    });
  };

  //用户密码重置
  const handleResetPwd = (userId) => {
    modal.confirm({
      title: '确认重置密码？',
      content: '密码将会重置为配置的初始值，请确认？',
      onOk: () => {
        resetUserPassword(userId).then(() => {
          message.success("用户密码重置成功！");
        });
      }
    });
  };
  // 处理用户分页变化
  const handleUserTableChange = (page) => {
    if (selectedDepartment) {
      const searchValues = userSearchForm.getFieldsValue();
      fetchUsers(selectedDepartment, page.current, page.pageSize, searchValues);
    }
  };

  // 处理用户搜索
  const handleUserSearch = (values) => {
    if (selectedDepartment) {
      fetchUsers(selectedDepartment, 1, pagination.pageSize, values);
    }
  };

  // 初始化数据
  useEffect(() => {
    fetchDepartments();
    fetchRoles();
  }, []);

  // 处理部门数据变化，设置默认选中第一个部门
  useEffect(() => {
    if (departments.length > 0 && !selectedDepartment) {
      const firstDepartmentId = departments[0].id;
      setSelectedDepartment(firstDepartmentId);
      // 重置搜索条件并获取用户列表
      userSearchForm.resetFields();
      fetchUsers(firstDepartmentId);
    }
  }, [departments, selectedDepartment]);

  // 用户表格列定义
  const userColumns = [
    {
      title: '头像',
      dataIndex: 'avatar',
      key: 'avatar',
      render: (avatar) => <img src={avatar} alt="头像" style={{ width: '40px', height: '40px', borderRadius: '50%' }} />
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username'
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname'
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone'
    },
    {
      title: '性别',
      dataIndex: 'gender',
      key: 'gender',
      render: (gender) => (
        <Tag color={gender ? 'blue' : 'pink'}>
          {gender ? '男' : '女'}
        </Tag>
      )
    },
    {
      title: '状态',
      dataIndex: 'statusMean',
      key: 'statusMean'
    }
  ];

  if(hasElementAuth(['userEdit','userDelete','userResetPwd'])){
    userColumns.push({
      title: '操作',
      key: 'action',
      width: 300,
      render: (_, record) => (
        <Space>
          <AuthControl permission="userEdit">
            <Button icon={<EditOutlined />} onClick={() => showEditUserModal(record)}>编辑</Button>
          </AuthControl>
          <AuthControl permission="userDelete">
            <Button icon={<DeleteOutlined />} danger onClick={() => handleDeleteUser(record.userId)}>删除</Button>
          </AuthControl>
          <AuthControl permission="userResetPwd">
            <Button icon={<RetweetOutlined />} danger onClick={() => handleResetPwd(record.userId)}>重置密码</Button>
          </AuthControl>
        </Space>
      ),
    })
  }

  return (
    <Layout style={{ padding: '20px', background: 'none' }}>
      {/* 左侧部门树 */}
      <Sider 
        width="40vh" 
        style={{ 
          padding: '20px',
          borderRadius: '8px',
          marginRight: '20px'
        }}
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '16px' }}>
          <h3>部门结构</h3>
          <Space>
            <AuthControl permission="departmentAdd">
              <Button 
                type="primary" 
                icon={<PlusOutlined />} 
                loading={loading}
                onClick={showAddModal}
              />
            </AuthControl>
            <AuthControl permission="departmentEdit">
              <Button 
                icon={<EditOutlined />} 
                onClick={showEditModal}
                disabled={!selectedDepartment}
              />
            </AuthControl>
            <AuthControl permission="departmentDelete">
              <Button 
                icon={<DeleteOutlined />} 
                danger
                onClick={handleDeleteDepartment}
                disabled={!selectedDepartment}
              />
            </AuthControl>
          </Space>
        </div>
        
        {departments.length > 0 ? (
          <Tree
            treeData={departments}
            showIcon
            fieldNames={{
              title: 'departmentName',
              key: 'id'
            }}
            defaultExpandAll
            onSelect={handleDepartmentSelect}
            selectedKeys={selectedDepartment ? [selectedDepartment] : departments.length > 0 ? [departments[0].id] : []}
            loading={loading}
          />
        ) : (
          <p>暂无部门数据</p>
        )}
      </Sider>
      
      {/* 右侧用户列表 */}
      <Content>
        <Card 
          title={
            <Space>
              <UserOutlined />
              <span>用户列表</span>
            </Space>
          }
          extra={
            selectedDepartment && (
              <AuthControl permission="userAdd">
                <Button loading={userLoading} type="primary" icon={<PlusOutlined />}  onClick={showAddUserModal}>
                  添加用户
                </Button>
              </AuthControl>
            )
          }
        >
          {selectedDepartment ? (
            <>
              {/* 用户搜索表单 */}
              <AuthControl permission="userSearch">
                <Form
                  form={userSearchForm}
                  layout="inline"
                  onFinish={handleUserSearch}
                  style={{ marginBottom: '16px' }}
                >
                  <Form.Item
                    name="username"
                    label="用户名"
                  >
                    <Input placeholder="请输入用户名" />
                  </Form.Item>
                  
                  <Form.Item
                    name="nickname"
                    label="昵称"
                  >
                    <Input placeholder="请输入昵称" />
                  </Form.Item>
                  
                  <Form.Item>
                    <Button 
                      type="primary" 
                      htmlType="submit"
                      loading={userLoading}
                      icon={<SearchOutlined />}
                    >
                      查询
                    </Button>
                  </Form.Item>
                  
                </Form>
              </AuthControl>
              {/* 用户表格 */}
              <Table
                columns={userColumns}
                dataSource={users}
                rowKey="userId"
                loading={userLoading}
                scroll={{ y: '40vh' }}
                pagination={{
                  ...pagination,
                  showTotal: (total) => `共 ${total} 条数据`,
                  showSizeChanger: true,
                  pageSizeOptions: ['5','10', '20', '50']
                }}
                onChange={handleUserTableChange}
              />
            </>
          ) : (
            <p>请选择一个部门查看用户</p>
          )}
        </Card>
      </Content>

      {/* 部门编辑模态框 */}
      <Modal
        title={modalType === 'add' ? '添加部门' : '编辑部门'}
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        onOk={() => departmentForm.submit()}
      >
        <DepartmentForm 
          form={departmentForm} 
          onFinish={handleDepartmentSubmit}
        />
      </Modal>

      {/* 用户编辑模态框 */}
      <Modal
        title={userModalType === 'add' ? '添加用户' : '编辑用户'}
        open={isUserModalVisible}
        onCancel={() => setIsUserModalVisible(false)}
        onOk={() => userForm.submit()}
        width={600}
      >
        <UserForm 
          form={userForm} 
          onFinish={handleUserSubmit}
          roles={roles}
          departmentId={selectedDepartment}
          isEditing={userModalType === 'edit'}
          departments={departments}
        />
      </Modal>
    </Layout>
  );
};

export default DepartmentIndex;